package cola.rh.System.common.security;

import cola.rh.System.Entity.User;
import cola.rh.System.Service.MenuService;
import cola.rh.System.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Name: UserDetailsServiceImpl
 * @Author: Cola
 * @Time: 2023/3/10 15:56
 * @Description: UserDetailsServiceImpl
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);
        if (null == user) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if (user.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        /*验证通过，构造 Authentication 对象*/
        List<String> userPermsList = menuService.findUserPermsList(user.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomUser(user, authorities);
    }
}
